<script setup>
import MainLayout from "~/layouts/MainLayout.vue";
import { useUserStore } from "~/stores/user.js";
const userStore = useUserStore();
const user = useSupabaseUser()

const posts = ref([])
const isPosts = ref(false)
const isLoading = ref(false)

watchEffect(()=> {
    if (!user.value) {
        return navigateTo('/auth')
    }
})

onBeforeMount(async ()=> {
    try {
        isLoading.value = true
        await userStore.getAllPosts()
        isLoading.value = false
    } catch (error) {
        console.log(error)
    }
})
onMounted(()=> {
    watchEffect(()=> {
        posts.value = userStore.posts
        if (userStore.posts && userStore.posts.length >= 1) {
            isPosts.value = true
        }else {
            isPosts.value = false
        }
    })
})
watch(()=> posts.value, ()=> {
    posts.value = userStore.posts
    if (userStore.posts && userStore.posts.length >= 1) {
        isPosts.value = true
    }else {
        isPosts.value = false
    }
}, {deep: true})
// const p = 'YfgULoXcxd0FuUTU'
</script>

<template>
    <MainLayout>
        <div id="indexPage" class="w-full overflow-auto">
            <div class="mx-auto max-w-[500px] overflow-hidden">
                <div id="posts" class="px-4 max-w-[600px] mx-auto">
                    <div class="text-white" v-if="isPosts" v-for="post in posts" :key="post">
                        <Post :post="post" @isDeleted="()=> posts = userStore.getAllPosts()" />
                    </div>
                    <div v-else>
                        <client-only>
                            <div v-if="isLoading" class="mt-20 w-full flex items-center justify-center mx-auto">
                                <div class="text-white mx-auto flex flex-col items-center justify-center">
                                    <Icon name="eos-icons:bubble-loading" size="50" class="text-white" />
                                    <span class="w-full mt-1">Loading...</span>
                                </div>
                            </div>

                            <div v-else class="mt-20 w-full flex items-center justify-center mx-auto">
                                <div class="text-white mx-auto flex flex-col justify-center items-center">
                                    <Icon name="tabler:mood-empty" size="50" class="text-white" />
                                    <span class="w-full">Make the first post!</span>
                                </div>
                            </div>
                        </client-only>
                    </div>
                </div>
            </div>
        </div>
    </MainLayout>
</template>

<style scoped>

</style>